﻿
$.fn.json_serialize = function () {
    var a = this.serializeArray();
    var $radio = $('input[type=radio],input[type=checkbox]', this);
    $.each($radio, function () {
        if ($("input[name='" + this.name + "']").is(':checked')) {
            console.log(this.name + " is checked!");
            for (var k = 0; k < a.length; k++) {
                if (a[k].name == this.name) {
                    a[k].value = true;
                    break;
                }
            }
        } else {
            var find = false;
            for (var k = 0; k < a.length; k++) {
                if (a[k].name == this.name) {
                    a[k].value = false;
                    find = true;
                    break;
                }
            }
            if (!find) {
                a.push({ name: this.name, value: false });
            }
        }
    });
    var $num = $('input[type=number]', this);
    $.each($num, function () {
        for (var k = 0; k < a.length; k++) {
            if (a[k].name == this.name) {
                a[k].value = Number(a[k].value);
                break;
            }
        }
    });

    var $snum = $('select', this);
    $.each($snum, function () {
        for (var k = 0; k < a.length; k++) {
            if (a[k].name == this.name) {
                a[k].value = Number(a[k].value);
                break;
            }
        }
    });
    return a;
};

$.fn.parseForm = function () {
    let serializeObj = {};
    let array = this.json_serialize();
    //let str = this.serialize();
    $(array).each(function () {
        if (serializeObj[this.name]) {
            if ($.isArray(serializeObj[this.name])) {
                serializeObj[this.name].push(this.value);
            } else {
                serializeObj[this.name] = [serializeObj[this.name], this.value];
            }
        } else {
            serializeObj[this.name] = this.value;
        }
    });
    return serializeObj;
};
//————————————————===================

var _waitloading=300;
function _apiget(httpurl, async, returnfunction) {

    var loadid = 0;
    var ajaxcompleted = false;
    var tickevent = function () {
        if (!ajaxcompleted) {
            if (typeof (layer) != "undefined") {
                loadid = layer.load();
            }
        }
    }
    setTimeout(tickevent, _waitloading);

    $.ajax({
        //提交数据的类型 POST GET
        type: "GET",
        //提交的网址
        url: httpurl,
        async: async,
        //提交的数据
        //data: postdata,
        //返回数据的格式
        datatype: "jsonp",//"xml", "html", "script", "json", "jsonp", "text".
        headers: {
            "token": readToken()
        },
        //在请求之前调用的函数
        beforeSend: function (request) {
        },
        //成功返回之后调用的函数
        success: function (data) {
            //console.log("执行到了success");
        },
        //调用执行后调用的函数
        complete: function (XMLHttpRequest, textStatus) {
            ajaxcompleted=true;
            _actioncallback(XMLHttpRequest, loadid, returnfunction);
        },
        //调用出错执行的函数
        error: function () {
            //请求出错处理
            //console.log("执行到了error");
        }
    });
}

/**
 * 使用query的方式传递查询参数
 * @param {*} url 没有?的url串
 * @param {*} _async 是否异步方式请求
 * @param {*} obj 查询的对象，比如{page:1,size:20}
 * @param {*} callback 回调函数
 */
function _apiquery(url, _async,obj, callback) {
    var loadid = 0;
    var ajaxcompleted = false;
    var tickevent = function () {
        if (!ajaxcompleted) {
            if (typeof (layer) != "undefined") {
                loadid = layer.load();
            }
        }
    }
    setTimeout(tickevent, _waitloading);
    if(obj!=null){
        var _querystr =(new URLSearchParams(obj)).toString();
        url = url +"?"+_querystr;
    }
    $.ajax({
        //提交数据的类型 POST GET
        type: "GET",
        //提交的网址
        url: url,
        async: _async,
        //返回数据的格式
        datatype: "jsonp",//"xml", "html", "script", "json", "jsonp", "text".
        headers: { "token": readToken() },
        //在请求之前调用的函数
        beforeSend: function (request) {
        },
        //成功返回之后调用的函数
        success: function (data) {
        },
        //调用执行后调用的函数
        complete: function (XMLHttpRequest, textStatus) {
            // console.log("complete");
            ajaxcompleted = true;
            _actioncallback(XMLHttpRequest, loadid, callback);
        },
        //调用出错执行的函数
        error: function () {
            //请求出错处理
            console.log("error");
        }
    });
}

function _apipost(httpurl, async, data, returnfunction) {
    var loadid = 0;
    var ajaxcompleted = false;
    var tickevent = function () {
        if (!ajaxcompleted) {
            if (typeof (layer) != "undefined") {
                loadid = layer.load();
            }
        }
    }
    setTimeout(tickevent, _waitloading);
    $.ajax({
        //提交数据的类型 POST GET
        type: "POST",
        //提交的网址
        url: httpurl,
        async: async,
        //提交的数据
        data: data,
        //返回数据的格式
        datatype: "jsonp",//"xml", "html", "script", "json", "jsonp", "text".
        headers: {
            "token": readToken()
        },
        contentType: "application/json; charset=UTF-8",
        //在请求之前调用的函数
        beforeSend: function (request) {
            //request.setRequestHeader("order", order);
        },
        //成功返回之后调用的函数
        success: function (data) {
            //console.log("执行到了success");
        },
        //调用执行后调用的函数
        complete: function (XMLHttpRequest, textStatus) {
            //console.log(XMLHttpRequest);
            ajaxcompleted=true;
            _actioncallback(XMLHttpRequest, loadid, returnfunction);

        },
        //调用出错执行的函数
        error: function () {
            //请求出错处理
            //console.log("执行到了error");
        }
    });
}

function _actioncallback(XMLHttpRequest, loadid, callback) {

    try {
        if (XMLHttpRequest.status == 401) {

            if (location.href.indexOf("/tick/page/") >= 0) {
                layer.msg("当前需要登陆后再操作！");
                window.parent.location.href = "/tick/page/login/index.html?t=" + (new Date()).getTime();
            }else if (location.href.indexOf("/task/page/") >= 0) {
                layer.msg("当前需要登陆后再操作！");
                window.parent.location.href = "/task/page/login/index.html?t=" + (new Date()).getTime();
            }else{
                window.parent.location.href = "/page/login/index.html?t=" + (new Date()).getTime();
            }

        } else if (XMLHttpRequest.status == 204) {
            if (typeof (layer) != "undefined") {
                layer.msg("查询数据为空");
            } else {
                alert("查询数据为空");
            }
        } else {

            if (XMLHttpRequest.status == 200) {
                // var result = JSON.parseXMLHttpRequest.responseText;
                var responsestr = XMLHttpRequest.responseText;
                if (responsestr[0] == "{" || responsestr[0] == "[") {
                    callback(XMLHttpRequest.status, JSON.parse(XMLHttpRequest.responseText));
                } else {
                    callback(XMLHttpRequest.status, (XMLHttpRequest.responseText));
                }
            } else {

                var responsestr = XMLHttpRequest.responseText;
                if (responsestr.length > 0) {

                    if (responsestr[0] == "{" || responsestr[0] == "[") {

                        var errinfo = JSON.parse(XMLHttpRequest.responseText);
                        if (errinfo.error) {
                            if (typeof (layer) != "undefined") {
                                layer.msg(errinfo.error.message);
                            } else {
                                alert(errinfo.error.message);
                            }
                        }
                        if (errinfo.message) {
                            if (typeof (layer) != "undefined") {
                                layer.msg(errinfo.message);
                            } else {
                                alert(errinfo.message);
                            }
                        }
                        callback(XMLHttpRequest.status, errinfo);
                    } else {
                        if (typeof (layer) != "undefined") {
                            // layer.closeAll();
                            layer.msg(responsestr);
                        } else {
                            alert(responsestr);
                        }

                        callback(XMLHttpRequest.status, responsestr);
                    }

                } else {

                    var errmessage = "请求API遇到一个错误！";

                    if (typeof (layer) != "undefined") {
                        // layer.closeAll();
                        layer.msg(errmessage);
                    } else {
                        alert(errmessage);
                    }
                }

            }

        }
    } catch {
    }
    if (loadid > 0) {
        if (typeof (layer) != "undefined") {
            layer.close(loadid);
        }
    }
}

function _apigetquery(key) {
    // 获取参数
    var url = window.location.search;
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}

function _apigetrandomstr(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}


function readToken() {
    return _locReadData("webtoken");
}
function saveToken(sval) {
    if (sval.length > 0) {
        _locSaveData("webtoken", sval);
    } else {
        localStorage.removeItem("webtoken");
    }
}


function _locSaveData(skey, sval) {

    localStorage.setItem(skey, sval);



}

function _locReadData(skey) {

    return localStorage.getItem(skey);
    return null;
}

//=====================================

/**
 * 打开编辑页面
 * @param {any} title
 * @param {any} url
 * @param {any} id
 * @param {any} w
 * @param {any} h
 */
function _showedit(title, url, id, w, h) {

    if (url.indexOf('?') > 0) {
        layer_show(title, url + "&id=" + id, w, h);
    } else {
        layer_show(title, url + "?id=" + id, w, h);
    }


}

/**
 * 
 * @param {*} title 
 * @param {*} url 
 * @param {*} w 
 * @param {*} h 
 */
function _showwindow(title, url, w, h) {
    layer_show(title, url, w, h);
}

/**
 * 打开新增页面
 * @param {any} title
 * @param {any} url
 * @param {any} w
 * @param {any} h
 */
function _showadd(title, url, w, h) {
    layer_show(title, url, w, h);
}

//Array的扩展
Array.prototype.indexOf = function (val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == val) return i;
	}
	return -1;
};

Array.prototype.remove = function (val) {
	var index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var state = [
    { id: 4, name: "已关闭" },
    { id: 5, name: "已完成" },
    { id: 6, name: "处理中" },
    { id: 7, name: "待结单" },
    { id: 8, name: "待确认" },
    { id: 9, name: "待补充" }
]
function returnSheetState(val) {
    var str = val
    for (var obj of state) {
        if (obj.id == val) { str = obj.name }
    }
    return str
}
if (typeof SheetState == "undefined") {
    var SheetState = {};
    SheetState.WaitReply = 9;
    SheetState.WaitSure = 8;
    SheetState.WaitFinish = 7;
    SheetState.Doing = 6;
    SheetState.Finish = 5;
    SheetState.Close = 4;
}

function isPicture(name){
    //判断是否是图片 - strFilter必须是小写列举
    var strFilter=".jpeg|.gif|.jpg|.png|.bmp|.pic|.webp|"
    if(name.indexOf(".")>-1){
        var p = name.lastIndexOf(".");
        var strPostfix=name.substring(p,name.length) + '|';        
        strPostfix = strPostfix.toLowerCase();
        if(strFilter.indexOf(strPostfix)>-1){return true;}
    }
    return false;            
}

function _readTypeModel(){
    _apiget("/api/ationshell/jobInfo?page=1&size=2000", false, function (code, obj) {
        $("[name=jobInfoId]").empty();
        if (code == 200) {
            var datas = obj.items;
            var htmlStr = "";
            for (var k = 0; k < datas.length; k++) {
                var item = datas[k];
                htmlStr += '<option value="' + item.id + '">' + item.projectDisplayName + '</option>';
            }
            $("[name=jobInfoId]").append(htmlStr);
        }
    });
}

/**
 * 根据javascript text/html构建对象，最多支持3级
 * @param {*} html 
 * @param {*} obj 
 * @returns 
 */
 function _buildtemplate(html, obj) {
    //\[([^\[\]]*?)\]
    var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm');
    // var html = document.getElementById("orderdetailhtml").innerHTML;
    var _innerhtml = html.replace(reg, function (node, key) {
        if (key.indexOf(":") > 0) {
            var keys = key.split(':');
            switch (keys.length) {
                case 2:{
                    if(obj[keys[0]]!=null){
                        return obj[keys[0]][keys[1]]
                    }else{
                        return "";
                    }
                };
                case 3:
                    {
                        if(obj[keys[0]]!=null){
                            if(obj[keys[0]][keys[1]]!=null){
                                return obj[keys[0]][keys[1]][keys[2]];
                            }else{
                                return "";
                            }
                        }else{
                            return "";
                        }


                    };
                case 4:
                    {
                        if(obj[keys[0]]!=null){
                            if(obj[keys[0]][keys[1]]!=null){
                                if(obj[keys[0]][keys[1]][keys[2]]!=null){
                                    return obj[keys[0]][keys[1]][keys[2]][keys[3]];
                                }else{
                                    return "";
                                }
                            }else{
                                return "";
                            }
                        }else{
                            return "";
                        }
                    };
                default: return obj[keys[0]][keys[1]];
            }
        } else {
            return obj[key];
        }
    });
    return _innerhtml;
}


/**
 * 前端验证
 * @param {*} elcselect 
 * @returns 
 */
function _beforeValidity(elcselect) {

    var findvalid = true;
    var fileds = $(elcselect)[0].querySelectorAll(":invalid");
    for (var k = 0; k < fileds.length; k++) {
        var namestr = fileds[k].name;
        var valinfo = fileds[k].validity;
        if (!valinfo.valid) {
            findvalid = false;
            if (valinfo.valueMissing) {
                layer.tips('当前项必须填写', elcselect + " [name=" + namestr + "]",{tipsMore:true},1);
            }
            if (valinfo.typeMismatch) {
                layer.tips('输入的数据类型不匹配，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }

            if (valinfo.patternMismatch) {
                layer.tips('输入的数据格式不匹配，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }

            if (valinfo.tooLong) {
                layer.tips('输入的数据位数过大，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }
            if (valinfo.tooShort) {
                layer.tips('输入的数据位数不足，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }

            if (valinfo.rangeOverflow) {
                layer.tips('输入的数据过大，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }

            if (valinfo.rangeUnderflow) {
                layer.tips('输入的数据过小，请按需输入', elcselect + " [name=" + namestr + "]", {tipsMore:true},1);
            }
        }
    }
    return findvalid;
}